#!/opt/chef/embedded/bin/ruby


# This script can be used to launch a xterm for each node in your deployment.

require 'optparse'
require 'json'
require 'erubis'

dname = ARGV[0]
keyfileloc = ARGV[1]
userid="idcuser"
groupid="idcgroup"
if ( ARGV[2] != nil )
	userid=ARGV[2]
end
if ( ARGV[3] != nil )
	groupid=ARGV[3]
end


def usage(exitcode)
    puts "Usage:  scripts/launchshells.rb <deployment-name> <private-key-file> [userid] [groupid]"
    exit exitcode
end

if ( dname == nil  )
    puts "Please provide a deployment name."
    usage(1)
end

if ( keyfileloc == nil  )
    puts "Please provide keyfile location."
    usage(2)
end

if ( ! File.file?("deployments/conf/#{dname}.json"))
    puts "Deployment file does not exist ./deployments/conf/#{dname}.json"
    usage(4)
end

if ( ! File.file?("#{keyfileloc}"))
    puts "Key file #{keyfileloc} does not exist"
    usage(5)
end

input = File.read('nodes/nodetemplate.json')
eruby = Erubis::Eruby.new(input)
json = File.read("deployments/conf/#{dname}.json")
depl = JSON.parse(json)

threads = []
depl['nodes'].each() do |node|
  threads << Thread.new(node) { |node|
  	output = `nohup scripts/launchshell.sh #{node["ip"]} #{keyfileloc} &`
    puts output
    if $? != 0
      node[:error] = true
    end
  }
end

